{% block content %}

<!-- 引入Bootstrap CSS和JS -->
<link href='{% static "bootstrap/bootstrap.min.css" %}' rel='stylesheet'>
<script src='{% static "bootstrap/jquery-3.6.0.min.js" %}'></script>
<script src='{% static "bootstrap/bootstrap.bundle.min.js" %}'></script>
<script src='{% static "fullcalendar/index.global.min.js" %}'></script>
<script src='{% static "fullcalendar/zh-cn.global.min.js" %}'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js'></script>
<link rel="stylesheet" href="{% static 'fullcalendar/fullcalendar.min.css' %}">
<style>
  #calendar {
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
  }
  .fc-event {
    border: none;
    border-radius: 6px;
    padding: 4px 8px;
    font-size: 0.875rem;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
    transition: transform 0.2s, box-shadow 0.2s;
  }
  .fc-event:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }
  .fc-toolbar button {
    border-radius: 0.375rem;
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
    border: 1px solid #dee2e6;
  }
  .fc-toolbar button:hover {
    background-color: #e9ecef;
  }
  .fc-daygrid-day-number {
    padding: 6px;
  }
  .fc-day-today {
    background-color: #f8f9fa !important;
  }
  .fc-toolbar-title {
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
</style>
<!-- 页面内容 -->
<div class="container mt-4 mb-6">
   <div class="card rounded-xl overflow-hidden shadow-xl border-0 mb-8">
      <div class="card-header bg-white border-bottom border-gray-100 px-4 py-3">
         <h2 class="h5 font-semibold text-gray-800 mb-0">课程安排日历</h2>
      </div>
      <div class="card-body p-0">
         <div id="calendar" class="w-100"></div>
      </div>
   </div>
</div>
 <!-- 班级课程创建模态框 -->
  <div class="modal fade" id="classCourseModal" tabindex="-1" aria-labelledby="classCourseModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="classCourseModalLabel">班级课程安排</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="classCourseForm" >
            {% csrf_token %}
            <input type="hidden" id="classCourseId" name="id">
            <input type="hidden" name="class_info" value="{{ class_id }}">
            <div class="mb-3">
              <label for="class_subject" class="form-label">班级学科</label>
              <select id="id_class_subject" name="class_subject" class="form-select rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition duration-200">
                {% for subject in class_subjects %}
                  <option value="{{ subject.id }}">{{ subject.name }}</option>
                {% endfor %}
              </select>
            </div>
            <div class="mb-3">
              <label for="weekday" class="form-label">星期几</label>
              <div class="rounded-lg border-gray-300 shadow-sm focus-within:border-primary focus-within:ring focus-within:ring-primary/20 transition duration-200">
                {{ class_course_form.weekday }}
              </div>
            </div>
            <div class="mb-3">
              <label for="course_period" class="form-label">课程时间段</label>
              <div class="rounded-lg border-gray-300 shadow-sm focus-within:border-primary focus-within:ring focus-within:ring-primary/20 transition duration-200">
                {{ class_course_form.course_period }}
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary rounded-lg px-4 py-2" data-bs-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-danger rounded-lg px-4 py-2" id="deleteClassCourseBtn" style="display: none;">删除</button>
          <button type="button" class="btn btn-primary rounded-lg px-4 py-2" id="saveClassCourseBtn">保存</button>
        </div>
      </div>
    </div>
  </div>


  <!-- 年级课程创建模态框 -->
  <div class="modal fade" id="gradeScheduleModal" tabindex="-1" aria-labelledby="gradeScheduleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="gradeScheduleModalLabel">年级课程安排</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="gradeScheduleForm" >
            {% csrf_token %}
            <input type="hidden" id="gradeScheduleId" name="id">
            <input type="hidden" name="grade" value="{{ grade.id }}">
            <input type="hidden" name="semester" value="{{ current_semester.id }}">
            <div class="mb-3">
              <label for="date" class="form-label">日期</label>
              <div class="rounded-lg border-gray-300 shadow-sm focus-within:border-primary focus-within:ring focus-within:ring-primary/20 transition duration-200">
                {{ grade_schedule_form.date }}
              </div>
            </div>
            <div class="mb-3">
              <label for="is_class_day" class="form-label">课程类型</label>
              <div class="rounded-lg border-gray-300 shadow-sm focus-within:border-primary focus-within:ring focus-within:ring-primary/20 transition duration-200">
                {{ grade_schedule_form.is_class_day }}
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary rounded-lg px-4 py-2" data-bs-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-danger rounded-lg px-4 py-2" id="deleteGradeScheduleBtn" style="display: none;">删除</button>
          <button type="button" class="btn btn-primary rounded-lg px-4 py-2" id="saveGradeScheduleBtn">保存</button>
        </div>
      </div>
    </div>
  </div>

 

<script>
    // *******************设置FullCalendar**************************
  $(document).ready(function() {
      const calendarEl=$('#calendar')[0];
      const calendar=new FullCalendar.Calendar(calendarEl,{
        locale:'zh-cn',
        initialView:'dayGridMonth',
        slotMinTime: '07:00:00',
        slotMaxTime: '23:00:00',
        headerToolbar: {
          left: 'prev,next today addClassCourseBtn addGradeScheduleBtn',
          center: 'title',
          right: 'dayGridMonth,timeGridWeek,timeGridDay,multiMonthYear'
        },
        customButtons: {
          addClassCourseBtn: {
            text: '添加班级课程',
            click: function() {
              // 清空ID，表示新建
              $('#classCourseId').val('');
              // 隐藏删除按钮
              $('#deleteClassCourseBtn').hide();
              // 显示班级课程安排模态框
              $('#classCourseModal').modal('show');
            }
          },
          addGradeScheduleBtn: {
            text: '添加年级课程',
            click: function() {
              // 清空ID，表示新建
              $('#gradeScheduleId').val('');
              // 隐藏删除按钮
              $('#deleteGradeScheduleBtn').hide();
              // 设置当前日期
              const today = new Date().toISOString().split('T')[0];
              $('#id_date').val(today);
              // 显示年级课程安排模态框
              $('#gradeScheduleModal').modal('show');
            }
          }
        },
        views: {
          dayGridMonth: {
            titleFormat: { year: 'numeric', month: 'long' }
          },
          timeGridWeek: {
            titleFormat: { year: 'numeric', month: 'long', week: 'numeric' }
          },
          timeGridDay: {
            titleFormat: { year: 'numeric', month: 'long', day: 'numeric' }
          },
          multiMonthYear: {
            titleFormat: { year: 'numeric' }
          }
        },
        eventSources: [
            {
              url: '{% url 'core:get_course_by_classid' class_id=class_id %}',
              color: 'blue',
              className: 'class-course-event'
            },
            {
              url: '{% url 'core:grade_schedule_by_gradeid' grade_id=grade_id %}',
              color: 'green',
              className: 'grade-schedule-event'
            }
          ],
          // 事件点击处理
          eventClick: function(info) {
            if (info.event.allDay==false) {
              // 处理班级课程事件点击
              classschedule(info);
            } else if (info.event.allDay==true) {
              // 处理年级课程事件点击
              gradeschedule(info);
            }
            
          },
          // 日期点击处理，用于创建新的年级课程安排
          dateClick: function(info) {
            // 清空ID，表示新建
            $('#gradeScheduleId').val('');
            // 隐藏删除按钮
            $('#deleteGradeScheduleBtn').hide();
            // 设置日期字段为选中的日期
            $('#id_date').val(info.dateStr);
            // 显示年级课程安排模态框
            $('#gradeScheduleModal').modal('show');
          }
      });
      calendar.render();

      // 班级课程事件处理函数
      function classschedule(info) {
        // 获取事件ID
        const eventId = info.event.id;
        if (eventId) {
          // 设置ID并显示删除按钮
          $('#classCourseId').val(eventId);
          $('#deleteClassCourseBtn').show();
          // 发送AJAX请求获取事件详情
          $.ajax({
            url: '{% url 'core:get_class_course_detail' pk=0 %}'.replace('0', eventId),
            type: 'GET',
            success: function(data) {
              // 填充表单数据
              $('#id_class_subject').val(data.class_subject);
              $('#id_weekday').val(data.weekday);
              $('#id_course_period').val(data.course_period);
              // 显示模态框
              $('#classCourseModal').modal('show');
            },
            error: function() {
              alert('获取班级课程详情失败');
            }
          });
        } else {
          // 新建事件
          $('#classCourseId').val('');
          $('#deleteClassCourseBtn').hide();
          $('#classCourseModal').modal('show');
        }
      }

      // 年级课程事件处理函数
      function gradeschedule(info) {
        // 获取事件ID
        const eventId = info.event.id;
        if (eventId) {
          // 设置ID并显示删除按钮
          $('#gradeScheduleId').val(eventId);
          $('#deleteGradeScheduleBtn').show();
          // 发送AJAX请求获取事件详情
          $.ajax({
            url: '{% url 'core:get_grade_schedule_detail' pk=0 %}'.replace('0', eventId),
            type: 'GET',
            success: function(data) {
              // 填充表单数据
              $('#id_date').val(data.date);
              $('#id_is_class_day').val(data.is_class_day);
              // 显示模态框
              $('#gradeScheduleModal').modal('show');
            },
            error: function() {
              alert('获取年级课程详情失败');
            }
          });
        } else {
          // 新建事件
          $('#gradeScheduleId').val('');
          $('#deleteGradeScheduleBtn').hide();
          // 设置日期为点击的日期
          const selectedDate = info.dateStr;
          $('#id_date').val(selectedDate);
          $('#gradeScheduleModal').modal('show');
        }
      }

      // 保存班级课程
      $('#saveClassCourseBtn').click(function() {
        const formData = $('#classCourseForm').serialize();
        const url = $('#classCourseId').val() ? '{% url 'core:update_class_course' pk=0 %}'.replace('0', $('#classCourseId').val()) : '{% url 'core:class_course_create' %}';
        $.ajax({
          url: url,
          type: 'POST',
          data: formData,
          success: function(response) {
            if (response.status === 'success') {
              // 重新加载日历事件
              calendar.refetchEvents();
              // 关闭模态框
              $('#classCourseModal').modal('hide');
              alert('保存成功');
            } else {
              // 显示错误信息
              let errorMsg = '保存失败: ';
              for (const field in response.errors) {
                errorMsg += '\n' + field + ': ' + response.errors[field].join(' ');
              }
              alert(errorMsg);
            }
          },
          error: function(xhr) {
            try {
              const response = JSON.parse(xhr.responseText);
              let errorMsg = '保存失败: ';
              if (response.errors) {
                for (const field in response.errors) {
                  errorMsg += '\n' + field + ': ' + response.errors[field].join(' ');
                }
              } else {
                errorMsg += response.message || '未知错误';
              }
              alert(errorMsg);
            } catch (e) {
              alert('保存失败: 服务器错误');
            }
          }
        });
      });

      // 保存年级课程
      $('#saveGradeScheduleBtn').click(function() {
        const formData = $('#gradeScheduleForm').serialize();
        const url = $('#gradeScheduleId').val() ? '{% url 'core:grade_schedule_update' pk=0 %}'.replace('0', $('#gradeScheduleId').val()) : '{% url 'core:grade_schedule_create' %}';
        $.ajax({
          url: url,
          type: 'POST',
          data: formData,
          success: function(response) {
            if (response.status === 'success') {
              // 重新加载日历事件
              calendar.refetchEvents();
              // 关闭模态框
              $('#gradeScheduleModal').modal('hide');
              alert('保存成功');
              calendar.refetchEvents();
            } else {
              // 显示错误信息
              let errorMsg = '保存失败: ';
              for (const field in response.errors) {
                errorMsg += '\n' + field + ': ' + response.errors[field].join(' ');
              }
              alert(errorMsg);
            }
          },
          error: function(xhr) {
            try {
              const response = JSON.parse(xhr.responseText);
              let errorMsg = '保存失败: ';
              if (response.errors) {
                for (const field in response.errors) {
                  errorMsg += '\n' + field + ': ' + response.errors[field].join(' ');
                }
              } else {
                errorMsg += response.message || '未知错误';
              }
              alert(errorMsg);
            } catch (e) {
              alert('保存失败: 服务器错误');
            }
          }
        });
      });

      // 删除班级课程
      $('#deleteClassCourseBtn').click(function() {
        if (confirm('确定要删除这个班级课程吗？')) {
          const eventId = $('#classCourseId').val();
          $.ajax({
            url: '{% url 'core:delete_class_course' pk=0 %}'.replace('0', eventId),
            type: 'POST',
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'}, 
            success: function() {
              // 重新加载日历事件
              calendar.refetchEvents();
              // 关闭模态框
              $('#classCourseModal').modal('hide');
              alert('删除成功');
            },
            error: function() {
              alert('删除失败');
            }
          });
        }
      });

      // 删除年级课程
      $('#deleteGradeScheduleBtn').click(function() {
        if (confirm('确定要删除这个年级课程吗？')) {
          const eventId = $('#gradeScheduleId').val();
          $.ajax({
            url: '{% url 'core:grade_schedule_delete' pk=0 %}'.replace('0', eventId),
            type: 'POST',
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
            success: function() {
              // 重新加载日历事件
              calendar.refetchEvents();
              // 关闭模态框
              $('#gradeScheduleModal').modal('hide');
              alert('删除成功');
            },
            error: function() {
              alert('删除失败');
            }
          });
        }
      });
      // 阻止默认链接行为
      document.getElementById('create_class_course_btn').addEventListener('click', function(e) {
        e.preventDefault();
        $('#classCourseId').val('');
        $('#deleteClassCourseBtn').hide();
        $('#classCourseModal').modal('show');
      });

      document.getElementById('create_grade_schedule_btn').addEventListener('click', function(e) {
        e.preventDefault();
        $('#gradeScheduleId').val('');
        $('#deleteGradeScheduleBtn').hide();
        $('#gradeScheduleModal').modal('show');
      });

     
  });
</script>
{% endblock %}


